package com.zh.harmony.mvvm;

import com.zh.harmony.mvvm.ability.ComponentAbility;
import com.zh.harmony.mvvm.slice.ComponentAbilitySlice;
import com.zh.harmony.viewmodel.ViewModelProvider;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityPackage;

/**
 * ViewModelProvider工具类
 */
public class ViewModelProviders {
    /**
     * 私有构造
     */
    private ViewModelProviders() {
    }

    /**
     * 从Ability中，获取AbilityPackage
     */
    private static AbilityPackage checkApplication(Ability ability) {
        AbilityPackage application = ability.getAbilityPackage();
        if (application == null) {
            throw new IllegalStateException("Your ability is not yet attached to "
                    + "Application. You can't request ViewModel before onCreate call.");
        }
        return application;
    }

    /**
     * 从ComponentAbilitySlice中，获取Ability
     */
    private static Ability checkAbility(ComponentAbilitySlice slice) {
        Ability activity = slice.getAbility();
        if (activity == null) {
            throw new IllegalStateException("Can't create ViewModelProvider for detached ComponentAbilitySlice");
        }
        return activity;
    }

    /**
     * 创建一个在ComponentAbilitySlice范围的ViewModelProvider
     */
    public static ViewModelProvider of(ComponentAbilitySlice slice) {
        return of(slice, null);
    }

    /**
     * 创建一个在ComponentAbility范围的ViewModelProvider
     */
    public static ViewModelProvider of(ComponentAbility ability) {
        return of(ability, null);
    }

    /**
     * 创建一个在ComponentAbilitySlice范围的ViewModelProvider
     *
     * @param factory ViewModel工厂，如果为null，默认使用HarmonyViewModelFactory
     */
    public static ViewModelProvider of(ComponentAbilitySlice slice, ViewModelProvider.Factory factory) {
        AbilityPackage application = checkApplication(checkAbility(slice));
        if (factory == null) {
            factory = ViewModelProvider.HarmonyViewModelFactory.getInstance(application);
        }
        return new ViewModelProvider(slice.getViewModelStore(), factory);
    }

    /**
     * 创建一个在ComponentAbility范围的ViewModelProvider
     *
     * @param factory ViewModel工厂，如果为null，默认使用HarmonyViewModelFactory
     */
    public static ViewModelProvider of(ComponentAbility activity,
                                       ViewModelProvider.Factory factory) {
        AbilityPackage application = checkApplication(activity);
        if (factory == null) {
            factory = ViewModelProvider.HarmonyViewModelFactory.getInstance(application);
        }
        return new ViewModelProvider(activity.getViewModelStore(), factory);
    }

    /**
     * 默认工厂
     */
    @SuppressWarnings("WeakerAccess")
    @Deprecated
    public static class DefaultFactory extends ViewModelProvider.HarmonyViewModelFactory {
        @Deprecated
        public DefaultFactory(AbilityPackage application) {
            super(application);
        }
    }
}